package com.narbeshuber.tablet.lasalara.http;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.narbeshuber.tablet.lasalara.LasaLaraActivity;
import com.narbeshuber.tablet.lasalara.R;
import com.narbeshuber.tablet.lasalara.fragment.ChapterFragment;
import com.narbeshuber.tablet.lasalara.fragment.QuestionFragment;
import com.narbeshuber.tablet.lasalara.listadapters.ChapterAdapter;
import com.narbeshuber.tablet.lasalara.model.Chapter;
import com.narbeshuber.tablet.lasalara.model.Question;

public class GetQuestionsTask extends AsyncTask<String, Object, String>{

	LasaLaraActivity lasalaraActivity;
	ProgressDialog dialog;
	Chapter chapter;
	public GetQuestionsTask(LasaLaraActivity lasalaraActivity, Chapter chapter){
		this.lasalaraActivity = lasalaraActivity;
		this.chapter = chapter;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(lasalaraActivity, "", "Downloading questions. Please wait...", true);
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://1.narbeshuber.appspot.com/getquestions");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("ck", chapter.getChapterKey()));
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is, 700);				 				
			ByteArrayBuffer baf = new ByteArrayBuffer(20);
			int current = 0;
			while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}		
			final String retval = new String(baf.toByteArray());
			return retval;
		} catch (Exception e) {
			Log.e("Exception: ", e.getMessage());
		}
		return "";
	}

	 protected void onPostExecute(String result) {
		dialog.dismiss();
		Log.e("minuviga", result);
		try {
			JSONObject o = new JSONObject(result);
			JSONArray questionsArray = o.getJSONArray("questions");
			JSONArray answersArray = o.getJSONArray("answers");
			LinkedList<Question> questions = new LinkedList<Question>();
			lasalaraActivity.getDbHelper().beginTransaction();
			for (int i = 0; i < questionsArray.length(); i++) {
				Question question = new Question();
				question.setChapterKey(chapter.getChapterKey());
				question.setQuestion(questionsArray.getString(i));
				question.setAnswer(answersArray.getString(i));
				question.setShowDate(null);
				question.setTimesAnswered(0);
				lasalaraActivity.getDbHelper().insertQuestion(question);
			}
			questions = lasalaraActivity.getDbHelper().getAllQuestionsFromChapter(chapter.getChapterKey());
			lasalaraActivity.getDbHelper().endTransaction();
			lasalaraActivity.getDbHelper().setCountsForChapter(chapter);
			Log.e("suurus:", Integer.toString(questions.size()));
	        FragmentManager fragmentManager = lasalaraActivity.getFragmentManager();
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			QuestionFragment questionFragment = new QuestionFragment(lasalaraActivity, questions);
			fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			fragmentTransaction.replace(R.id.right, questionFragment);
			ChapterAdapter chapterAdapter = (ChapterAdapter)ChapterFragment.getInstance().getListAdapter();
			chapterAdapter.notifyDataSetChanged();
			fragmentTransaction.commit();
		} catch (JSONException e) {
			Log.e("Exception: ", e.getMessage());
		}
     }
}
